package com.irisking.server;
import com.irisking.server.callback.IDispatcher;
import com.irisking.server.client.ClientManager;

import com.irisking.server.client.DeviceClient;
import com.irisking.server.entity.TransforData;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.net.InetSocketAddress;

/**
 * 消息接受处理类
 * @author -weiz-
 *
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<TransforData> {

    private IDispatcher dispatcherCallBack;
    public NettyServerHandler(IDispatcher dispatcherCallBack){
        this.dispatcherCallBack = dispatcherCallBack;
    }


    /**
     * 接收消息
     */
    @Override
    protected void messageReceived(ChannelHandlerContext ctx, TransforData recvData) throws Exception {
        handlerMessage(ctx, recvData);
    }

	/**
	 * 消息处理
	 * @param ctx
	 * @param recvData
	 */
	private void handlerMessage(ChannelHandlerContext ctx, TransforData recvData) {
		System.out.println("handlerMessage  module:" + recvData.getCommCode() + " ,cmd:" + recvData.getCommSubCode() + ",data:" + recvData.getData().length);
		// 生成设备连接唯一标识
		String key = getConnectKey(ctx);
        //ClientManager.heartBeat(key);
        dispatcherCallBack.dispatcher(recvData.getCommCode(),key,recvData.getData());
	}


    /**
     * 客户端接入
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("客户端接入");
        DeviceClient deviceClient = new DeviceClient(ctx.channel());
        String key =getConnectKey(ctx);
        System.out.println(key);
        ClientManager.put(key,deviceClient);
    }

    private String getConnectKey(ChannelHandlerContext ctx){
        InetSocketAddress socket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = socket.getAddress().getHostAddress();
        String clientPort = String.valueOf(socket.getPort());
        String key = clientIP + ":" + clientPort;
        return key;
    }

	/**
	 * 断线断开，移除会话
	 */
    @Override
	public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("设备离线");
        String key = getConnectKey(ctx);
        System.out.println(key);
        dispatcherCallBack.offline(key);
        ClientManager.remove(key);
    }

    /**
     * 异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常了。。。。。");
        cause.printStackTrace();
        dispatcherCallBack.caughtException(cause);
        ctx.close();
    }
}
